package 设计模式.观察者模式.demo2;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName EventListener
 * @Description 事件监听器，被观察者的抽象
 */
public class EventListener {
    protected Map<String, Event> events = new HashMap<String,Event>();

    public void addListener(String eventType, Object target, Method callback){
        events.put(eventType,new Event(target,callback));
    }
    public void addListener(String eventType, Object target){
        try{
            this.addListener(eventType,target,target.getClass().getMethod("on"+ toUpperFirstCase(eventType),Event.class));

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String toUpperFirstCase(String eventType) {
        char [] chars = eventType.toCharArray();
        if(chars[0]> 'a' && chars[0] < 'z'){
            chars[0] -= 32;
        }
        return String.valueOf(chars);
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try{
            if(null != event.getCallback()){
                //反射调用 回调函数
                event.getCallback().invoke(event.getTarget(),event);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void trigger(String trigger){
        if(!this.events.containsKey(trigger)){return;}
        //如果已进行注册，回调
        trigger(this.events.get(trigger).setTrigger(trigger));

    }
}
